#!/user/bin/env python
# -*- coding: utf-8 -*-
''' 
Author: Sjy
LastEditTime: 2024-12-16 10:28:14
Description: 
'''

__all__= []

import os
import gui.controls.envs as envs

# from .uis import ImportMainModel

global PATH_PLUGIN
PATH_PLUGIN = "data/ipimas"
global FILE_INPUT # 算例输出的参数文件
FILE_INPUT = f"{PATH_PLUGIN}/input.json"

global FILE_CONFIG # 算例输出的参数文件
FILE_CONFIG = f"{PATH_PLUGIN}/config.json"

if not os.path.exists(PATH_PLUGIN):
    # 递归的创建文件夹
    os.makedirs(PATH_PLUGIN)
    
class Actions:
    """保存算例需要的数据"""
    def save_data(data, file:str=FILE_INPUT, encoding:str="gbk", delKeys=[], update=True) -> None:
        """保存数据
        Args:
            data (dict): 保存的数据
            file (str, optional): 文件路径. Defaults to FILE_INPUT.
            encoding (str, optional): 编码. Defaults to "gbk".
            delKeys (list, optional): 删除的key. Defaults to [].    
        Returns:
            None
        """
        # update_data 仅能做到简单的key的覆盖更新 无法处理深层次的 列表中数据更新 因此需要更换成更通用的数据更新方法
        # saveData = envs.utils.update_data(envs.UFile.open_json(file, encoding=encoding) or {}, data, delKeys=delKeys)
        saveData = data
        if update:
            saveData = envs.utils.recursion_update_data(envs.UFile.open_json(file, encoding=encoding) or {}, data, delKeys=delKeys)
        envs.UFile.save_json(file, saveData, encoding=encoding)

    def get_data(file:str=FILE_INPUT, encoding:str="gbk") -> dict:
        """获取数据
        Args:
            file (str, optional): 文件路径. Defaults to FILE_INPUT.
            encoding (str, optional): 编码. Defaults to "gbk".
        Returns:
            dict : 返回数据
        """
        try:
            return envs.UFile.open_json(file, encoding=encoding) or {}
        except:
            pass
        return {}
    def show_inp(file:str="") -> None:
        """显示inp模型
        Args:
            file (str, optional): 文件路径.
        Returns:
            None
        """
        envs.apis.open_inp(file)
    def open_file(file:str="") -> None:
        """用系统命令打开文件
        Args:
            file (str, optional): 文件路径. 
        Returns:
            None
        """
        envs.UFile.open_file(file)
    def update_tree(key:str):
        """更新 tree 中对应位置节点的数据信息
        Args:
            key (str, optional): key 由dock中设置判定.
        Returns:
            None
        """
        envs.ipimas_updateModelTree(key)
    def show_model(inpFile:str=""):
        """显示模型
        Args:
            inpFile (str, optional): inp 文件路径.
        Returns:
            None
        """
        if not inpFile:return
        # 利用接口文件显示模型 
        envs.apis.open_inp(inpFile)
    def assign_run_file() -> None:
        """指定执行程序文件
        Args:
            None
        Returns:
            None
        """
        fileInfo = envs.UFile.import_custom_type_file("BAT Files (*.bat);; EXE Files (*.exe)", file= "", parent=envs.GL.get_value("py3d"))
        if not fileInfo:return
        file = fileInfo.get("file")
        data = envs.UFile.open_json(FILE_CONFIG)
        data["run_file"] = file
        Actions.save_data(data, FILE_CONFIG, encoding="utf-8")
        envs.MBox.success("保存成功")
    def run_cmd() -> None:
        """运行
        Args:
            None
        Returns:
            None
        """
        data = Actions.get_data(FILE_CONFIG, encoding="utf-8") or {}
        run_file = data.get("run_file")
        if not run_file:return envs.MBox.warning("请先指定执行程序文件")
        # 检查本地文件是否存在
        if not os.path.exists(run_file):
            return envs.MBox.warning("当前执行程序文件不存在, 请重新指定")
        # envs.run_cmd(data["file"])
        cmd = f"start  {envs.utils.quote_path_with_spaces(run_file)}"
        path = PATH_PLUGIN
        envs.apis.pexecute(cmd, cwd=path, shell=True, isEmit=True)
        envs.MBox.success("已开始执行程序！")
    def show_run_result() -> None:
        """显示结果
        Args:
            None
        Returns:
            None
        """
        dictFile = envs.UFile.import_custom_type_file("VTK Files (*.vtk);;VTU Files (*.vtu)")
        if dictFile:
            extension = dictFile.get("extension")
            file = dictFile.get("file")
            if extension == ".vtk":
                return envs.apis.open_vtk(file)
            elif extension == ".vtu":
                return envs.apis.open_vtu(file)
            

    def get_cae_failure_areas() -> list:
        """获取CAE 失效区域
        Args:
            data (dict, optional): 分析模型数据. Defaults to {}.
        Returns:
            list: 失效区域
        """
        return [
            {
                "title": "set-1, solid",
                "value": "set-1, solid"
            },
            {
                "title": "set2, shell",
                "value": "set2, shell"
            }
        ]